package club.cearnach.api.service.impl;

import club.cearnach.api.dao.INewsDao;
import club.cearnach.api.dto.NewsDTO;
import club.cearnach.api.exception.MovieNewsException;
import club.cearnach.api.exception.MoviePathException;
import club.cearnach.api.form.PageBean;
import club.cearnach.api.service.INewsService;
import club.cearnach.api.util.FileUtil;
import club.cearnach.core.property.MovieWebProperties;
import club.cearnach.entity.News;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author 阮胜
 * @date 2018/5/17 14:49
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class NewsServiceImpl implements INewsService {

    private final INewsDao newsDao;

    public NewsServiceImpl(INewsDao newsDao) {
        this.newsDao = newsDao;
    }

    @Autowired
    private MovieWebProperties movieWebProperties;

    @Override
    public Page<News> findAllOrderByCreateDateDesc(PageBean pageBean) {
        return newsDao.findAllByOrderByCreateDateDesc(PageRequest.of(pageBean.getPage(), pageBean.getSize()));
    }


    @Override
    public News save(NewsDTO newsDTO) throws IOException, MoviePathException {
        News news = new News();
        BeanUtils.copyProperties(newsDTO, news);
        MultipartFile file = newsDTO.getImageFile();
        if (file != null) {
            String fileName = FileUtil.saveFile(file, movieWebProperties.getUpload().getPersonImagePath());
            news.setImageFileName(fileName);
        }
        return newsDao.save(news);
    }

    @Override
    public void delete(Integer id) {
        newsDao.findById(id).ifPresent(news -> newsDao.deleteById(id));
    }

    @Override
    public long deleteIn(Integer[] idArr) {
        long result = 0;
        for (int id : idArr) {
            try {
                newsDao.deleteById(id);
                result++;
            } catch (Exception e) {
                e.printStackTrace();
                log.error(e.getMessage());
            }
        }
        return result;
    }

    @Override
    public News findById(Integer id) throws MovieNewsException {
        return newsDao.findById(id).orElseThrow(MovieNewsException::new);
    }

    @Override
    public Long count() {
        return newsDao.count();
    }

    @Override
    public News findLastNews() {
        return newsDao.findTop1ByOrderByCreateDateDesc();
    }
}

